﻿using System.Windows.Media.Imaging;
using System.IO;
using System.Runtime.Serialization;
using System;

namespace WebSilverlight.Helpers
{
    [DataContract]
    public partial class PictureSerializableHelper
    {
        public PictureSerializableHelper(){}

        public PictureSerializableHelper(WriteableBitmap bmp)
        {
            this.Pixels = bmp.Pixels;
            this.PixelHeight = bmp.PixelHeight;
            this.PixelWidth = bmp.PixelWidth;
        }       

        [DataMember]
        public int[] Pixels { get; set; }
        [DataMember]
        public int PixelWidth { get; set; }
        [DataMember]
        public int PixelHeight { get; set; }       
    }

    public class PictureHelper
    {        
        public static WriteableBitmap WriteableBitmapFromByteArray(byte[] buffer)
        {            
            WriteableBitmap bmp = null;
            if (buffer != null && buffer.Length > 0)
            {
                MemoryStream ms = new MemoryStream(buffer);
                try
                {                    
                    DataContractSerializer ser = new DataContractSerializer(typeof(PictureSerializableHelper));
                    PictureSerializableHelper hlp = (PictureSerializableHelper)ser.ReadObject(ms);

                    bmp = new WriteableBitmap(hlp.PixelWidth, hlp.PixelHeight);

                    for (int i = 0; i < hlp.Pixels.Length; i++)
                    {
                        bmp.Pixels[i] = hlp.Pixels[i];
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    ms.Close();
                }                                
            }
            return bmp;
        }

        public static byte[] ToByteArray(WriteableBitmap bmp)
        {
            PictureSerializableHelper hlp = new PictureSerializableHelper(bmp);

            MemoryStream ms = new MemoryStream();
            DataContractSerializer ser = new DataContractSerializer(typeof(PictureSerializableHelper));
            ser.WriteObject(ms, hlp);
            byte[] array = ms.ToArray();            
            ms.Close();

            return array;
            /*
            byte[] retorno = new byte[array.Length];
            for (int i = 0; i < array.Length; i++)
            {
                retorno[i] = array[i];
            }

            return retorno;
             * */
        }
    }
}
